<?php
class Api_Lib_Rsp_Sample_Ruku {

    var $proPrev = 'OLP';
    function __construct() {
        $this->_modelExample = FLEA::getSingleton('Model_Sample_Ruku');
        $this->_subModel = FLEA::getSingleton('Model_Sample_Ruku2Product');
    }

    /**
     * 更新入库/插入库
     * Time：2019/11/11 10:31:54
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function updateSample($params,& $service){
        $form = json_decode($params['formData'] ,true);
        // 先验证参数
        $ruleRequired = array('kuweiId','cnt');
        foreach ($ruleRequired as $key => & $v) {
            if(!isset($form[$v]) || !$form[$v]){
                $service->send_user_error($v."参数必填");
            }
        }
        //查当前产品分类Id
        $kindIndex = $params['kindIndex'];
        //产品种类选项
        $modelProkind = FLEA::getSingleton("Model_Jichu_Prokind");
        $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
        $prokind = $modelProkind->getOptions();
        $fileds = array();
        $pro = array();
        $pro['proCode'] = $form['proCode'] ? $form['proCode'] : $this->CreateProCode($this->proPrev,'','jichu_product','proCode');
        $pro['proName'] = $form['proName'];
        $pro['productId'] = $form['productId']+0;
        $product = $modelProduct->find($pro['productId']);
        $proPrev = substr($product['proCode'],0,6);
        foreach ($prokind as $k => & $v) {
            if($k == $kindIndex){
                $pro['kindId'] = $v['value'];
                $fileds = $modelProkind->getFileds($v['value'] ,'all');
            }
        }
        foreach ($fileds as $ke => & $val) {
            $pro[$val['filed']] = $form[$val['filed']];
        }
        // dump($pro);exit;
        if($params['proStatus']){
            if($params['proStatus'] == 'add'){
                $pro['proCode'] = $this->CreateProCode($proPrev,'','jichu_product','proCode');
                $pro['prefix'] = $pro['proCode'];
                $pro['suffix'] = 0;
                $productId = $modelProduct->save($pro);
            }else{
                $pro['id'] = $form['productId'];
                $res = $modelProduct->save($pro);
                if($res){
                    $productId = $pro['id'];
                }
            }
        }else{
            if(empty($pro['productId'])){
                //如果有基础信息完全相同的产品获取它的id,否则就是新增产品
                $condition = array();
                $condition[] = array('proName',$pro['proName'],'=');
                $condition[] = array('kindId',$pro['kindId'],'=');
                foreach ($fileds as $key => & $va) {
                    $condition[] = array("{$va['filed']}","{$pro[$va['filed']]}",'=');
                }
                $product = $modelProduct->find($condition);
                if($product){
                    $productId = $product['id'];
                }else{
                    $products = $modelProduct->find(array('proCode'=>$pro['proCode']));
                    if($products['suffix']==0){
                        $pro['prefix'] = $pro['proCode'];
                    }else{
                        $pro['prefix'] = $products['prefix'];
                    }
                    $productId = $modelProduct->save($pro);
                }
            }else{
                //如果有基础信息完全相同的产品获取它的id,否则就是新增产品
                // $sql = "SELECT id from jichu_product where proName = '{$pro['proName']}' and kindId = '{$pro['kindId']}'";
                $condition = array();
                $condition[] = array('proName',$pro['proName'],'=');
                $condition[] = array('kindId',$pro['kindId'],'=');
                $condition[] = array('id',$pro['productId'],'=');
                foreach ($fileds as $key => & $va) {
                    $condition[] = array("{$va['filed']}","{$pro[$va['filed']]}",'=');
                }
                $product = $modelProduct->find($condition);
                if($product){
                    $productId = $product['id'];
                }else{
                    $ret = array('msg'=>'','success'=>true,'dialogIsUpdate'=>true);
                    echo json_encode($ret);exit;
                }
            }
        }
        //有些方法在controller中，这里调用
        $ctl = FLEA::getSingleton('Controller_Sample_Ruku');
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');

        // 如果有id,表示是修改，需要先获取原来的数据
        $ruku = array();
        if($form['sid'] > 0){
            $ruku = $this->_subModel->find($form['sid']);
        }

        //组织数据
        $data = array();
        $data['id']       = $ruku['rukuId'] + 0;
        $data['rukuCode'] = $form['rukuCode'] ? $form['rukuCode'] : $ctl->createNewCode();
        $data['rukuDate'] = $form['rukuDate'] ? $form['rukuDate'] : date('Y-m-d');
        $data['reason']   = strval($form['reason']);
        $data['purpose']  = strval($form['purpose']);
        $data['memo']     = strval($form['memo']);
        $data['creater']  = strval(($form['creater'] ? $form['creater'] : $params['creater']));

        //处理入库明细的信息
        $_product              = array();
        $_product['id']        = $form['sid'] + 0;
        $_product['productId'] = $productId + 0;
        $_product['kuweiId']   = $form['kuweiId'] + 0;
        $_product['cnt']       = $form['cnt'] + 0;
        $_product['type']      = strval($form['type']);
        $_product['proDesc']   = strval($form['proDesc']);
        $_product['gexing']    = strval($form['gexing']);
		$_product['zuzhi']     = strval($form['zuzhi']);
        $_product['tanli']     = strval($form['tanli']);
        // 后整理
        sort($form['hzlId']);
        $_product['hzlId'] = $form['hzlId'] ? join(',' ,$form['hzlId']) : '';

        //处理入库的图片信息
        if(is_array($form['imageId'])){
            $form['imageId'] = join(',' ,array_col_values($form['imageId'] ,'imageId'));
        }
        $_product['imageId']   = strval($form['imageId']);
        // $_product['code']      = strval($form['code']);
        //条码生成的
        // $form['code'] = strval($form['code']);
        $_product['code'] = '';
        $form['code'] = trim($form['code']);
        if($form['code']!=''){
            $match = "/^[a-zA-Z0-9-_\/]*$/";
            if(!preg_match($match,$form['code'])){
                return array('success'=>false ,'msg'=>'条码含有数字英文以外的字符');
            }else{
                if(strlen($form['code']) < 6){
                    return array('success'=>false ,'msg'=>'条码字符长度至少6位');
                }
            }
        }

        //条码规则：相同productId和产品编号，类型，条码保证一致
        //先查找该样品信息是否已经存在历史条码，如果已经存在，则直接使用历史条码
        $sql = "SELECT code from sample_ruku2product where productId='{$_product['productId']}' and id<>'{$_product['id']}' and proDesc='{$_product['proDesc']}' and type='{$_product['type']}' and gexing='{$_product['gexing']}' and zuzhi='{$_product['zuzhi']}' and tanli='{$_product['tanli']}' and hzlId='{$_product['hzlId']}' limit 0,1";
        $res = $this->_modelExample->findBySql($sql);
        $_code = strval($res[0]['code']);
        //生成条码
        if($form['code'] == ''){
            if($_code){
                $_product['code'] = $_code;
            }else{
                $_product['code'] = $this->_modelExample->createNewCode($_product);
            }
        }else{
            // 如果填写的条码和历史条码不一致，则需要提醒错误
            if($_code && $form['code']<>$_code){
                return array('msg'=>'该规格类型样品有产品条码('.$_code.')，留空系统自动使用','success'=>false);
            }
            //查找条码是否重复:相同的产品和类型允许重复，否则不允许
            $sql = "SELECT count(*) as cnt from sample_ruku2product where code='{$form['code']}' and (productId<>'{$_product['productId']}' or proDesc<>'{$_product['proDesc']}' or gexing<>'{$_product['gexing']}' or zuzhi<>'{$_product['zuzhi']}' or tanli<>'{$_product['tanli']}' or hzlId<>'{$_product['hzlId']}') and id<>'{$_product['id']}'";
            $res = $this->_modelExample->findBySql($sql);
            if($res[0]['cnt'] > 0){
                return array('msg'=>'条码已经被其他产品使用','success'=>false);
            }

            $_product['code'] = $form['code'];
        }
        //如果偶后缀的话需要保存后缀
        if(strstr($_product['code'],'-')){
            $pros = $modelProduct->find($_product['productId']);
            //追加后缀的时候需要判断前缀是否在条码中且条码长度大于前缀
            $mark = strripos($_product['code'],$pros['prefix']);
            $codeLength = strlen($_product['code']);
            $proLength = strlen($pros['prefix']);
            if($mark >= 0 && $codeLength > $proLength){
                $last = strrpos($_product['code'], '-');
                $_product['append'] = substr($_product['code'], $last+1);
            }else{
                $_product['append'] = 0;
            }
        }
        $data['Products'] = array($_product);
        // dump($data);exit;
        $result = $this->_modelExample->save($data);

        return array('success'=>$result ? true : false ,'msg'=>'入库完成');
    }

    // 获取条码汇总的入库记录
    function getRukuCodeList($params,& $service){
        $pageNum     = $params['pageNum'] ? $params['pageNum'] : 20;
        $currentPage = $params['page'] ? $params['page'] : 1;

        $sql="SELECT x.productId,x.type,x.proDesc,x.code,x.gexing,x.zuzhi,x.tanli,x.hzlId
              from sample_ruku2product x
              where 1 ";

        if($params['type']) {
            $sql.=" and x.type = '{$params['type']}'";
        }
        if($params['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$params['proDesc']}%'";
        }
        if($params['code']!='') {
            $sql.=" and x.code like '%{$params['code']}%'";
        }
        if($params['productId']) {
            $sql.=" and x.productId = '{$params['productId']}'";
        }
        if($params['kuweiId']) {
            $sql.=" and x.kuweiId = '{$params['kuweiId']}'";
        }
        $sql .=" group by x.productId,x.code order by x.productId asc,x.code asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pageNum ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            //产品明细
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['Product']  = $tmp[0];
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $_tRow = array();
            $modelProduct->filedValue3($_tRow ,$tmp[0] ,$filedsSingle);
            $v['productDesc'] = $_tRow;

            foreach ($_tRow as $tk => & $desc) {
                $v['otherDesc'][] = $tk.':'.$desc;
                $v['others'][] = array('title'=>$tk  ,'value'=>$desc);
            }
            $v['othersRows'] = ceil(count($v['others'])/2);//用户计算显示其他信息的行数

            $v['cnt'] = round($v['cnt'],6);

            // 后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join(',',array_col_values($tmp,'gongyiName'));
            }

            // 查找库存数据
            $v['kucunCnt'] = $modelKucun->getKucun(array(
                'productId' =>$v['productId'],
                'code'      =>$v['code'],
                'type'      =>$v['type'],
            ));

        }

        return array('row'=>$rowset,'page'=>$currentPage,'total'=>$pager->totalCount,'pageCount'=>count($rowset));
    }

    function checkCode($params){
        $arr = $params['formData'];
        $row = json_decode($arr,true);

        //1.拿所有属性去查是否有条码,如果有条码,判断和当前条码是否相同,如果相同不做提醒,如果不同,则提示留空自动使用历史条码
        //2.如果没有条码,则需判断当前条码是否存在,如果存在提醒条码存在,否则直接使用
        if($row['hzlId']){
            foreach($row['hzlId'] as $k => & $v){
                if($v==''){
                    unset($row['hzlId'][$k]);continue;
                }
            }
            $row['hzlId'] = array_values($row['hzlId']);
        }
        $row['hzlId'] = $row['hzlId'] ? implode(',', $row['hzlId']) : '';
        $sql = "SELECT code from sample_ruku2product where productId='{$row['productId']}' and proDesc='{$row['proDesc']}' and type='{$row['type']}' and gexing='{$row['gexing']}' and hzlId='{$row['hzlId']}' limit 0,1";
        $res = $this->_subModel->findBySql($sql);
        $_code = strval($res[0]['code']);
        //生成条码
        if($_code){
            if($_code==$row['code']){
                return array(
                    'success' =>true,
                    'msg'    =>'条码'.$row['code'].'可以使用',
                    'code'   =>$row['code']
                );
            }else{
                $ret = array('msg'=>'该规格类型样品有产品条码('.$_code.')，留空系统自动使用','success'=>false);
                return json_encode($ret);exit;
            }
        }else{
            $sql = "SELECT count(*) as cnt from sample_ruku2product where code = '{$row['code']}'";
            $res = $this->_modelExample->findBySql($sql);
            if($res[0]['cnt'] > 0){
                return array(
                    'success' =>false,
                    'msg'    =>'条码'.$row['code'].'已存在',
                );
            }else{
                return array(
                    'success' =>true,
                    'msg'    =>'条码'.$row['code'].'可以使用',
                    'code'   =>$row['code']
                );
            }
        }
    }

    /**
     * getRukuList
     * Time：2019/11/11 15:11:10
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function getRukuList($params,& $service){
        $pageNum     = $params['pageNum'] ? $params['pageNum'] : 20;
        $currentPage = $params['page'] ? $params['page'] : 1;

        $sql="SELECT x.*,y.rukuDate,y.rukuCode,y.reason,y.creater,y.purpose
              from sample_ruku2product x
              left join sample_ruku y on y.id=x.rukuId
              where 1 ";

        if($params['rukuCode']!='') {
            $sql.=" and y.rukuCode like '%{$params['rukuCode']}%'";
        }
        if($params['purpose']!='') {
            $sql.=" and y.purpose like '%{$params['purpose']}%'";
        }
        if($params['type']) {
            $sql.=" and x.type = '{$params['type']}'";
        }
        if($params['proDesc']!='') {
            $sql.=" and x.proDesc like '%{$params['proDesc']}%'";
        }
        if($params['code']!='') {
            $sql.=" and x.code like '%{$params['code']}%'";
        }
        if($params['reason']!='') {
            $sql.=" and y.reason like '%{$params['reason']}%'";
        }
        if($params['productId']) {
            $sql.=" and x.productId = '{$params['productId']}'";
        }
        if($params['kuweiId']) {
            $sql.=" and x.kuweiId = '{$params['kuweiId']}'";
        }
        if($params['dateFrom']){
            $sql .= " and y.rukuDate >= '{$params['dateFrom']}' and y.rukuDate <= '{$params['dateTo']}'";
        }
        $sql .=" order by y.id desc,x.id asc";

        // dump($sql);exit;
        FLEA::loadClass('TMIS_Pager');
        $pager = new TMIS_Pager($sql,null,null,$pageNum ,($currentPage - 1));
        $rowset = $pager->findAll();

        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $baseUrlstr = detect_uri_base();
        $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));
        // dump($rowset);exit;
        foreach ($rowset as $key => & $v) {
            $v['sid'] = $v['id'];
            unset($v['id']);

            //产品明细
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $_tRow = array();
            $modelProduct->filedValue3($_tRow ,$tmp[0] ,$filedsSingle);
            $v['productDesc'] = $_tRow;
            // $v['otherDesc'] = $modelProduct->filedOtherFormat($tmp[0] ,'text','' ,$filedsDefault);
            foreach ($_tRow as $tk => & $desc) {
                $v['otherDesc'][] = $tk.':'.$desc;
                $v['others'][] = array('title'=>$tk  ,'value'=>$desc);
            }
            $v['othersRows'] = ceil(count($v['others'])/2);//用户计算显示其他信息的行数


            $v['cnt'] = round($v['cnt'],6);

            $_tmp = $modelKuwei->find($v['kuweiId']);
            $v['kuweiName'] = $_tmp['kuweiName'];

            //图片预览
            if($v['imageId']){
                $sql = "SELECT * from jichu_image where id in({$v['imageId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                // $tmp = array_col_values($tmp,'path');
                foreach ($tmp as & $ii) {
                    $v['imageSrc'][] = array(
                        'path'=>$serverUrl .$ii['path'],
                    );
                }
            }

            //提供打印的url链接，在小程序里直接打卡h5进行打印
            $v['printUrl'] = url('Sample_Ruku','PrintAoEqinfo',array('id'=>$v['rukuId']),null,array('mode'=>'URL_STANDARD','bootstrap'=>'index.php'));

            // 后整理
            if($v['hzlId']){
                $sql = "SELECT * from jichu_gongyi where id in({$v['hzlId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                $v['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
            }else{
                $v['hzl'] = '';
            }
        }
        return array('row'=>$rowset,'page'=>$currentPage,'total'=>$pager->totalCount,'pageCount'=>count($rowset));
    }

    /**
     * 查询明细
     * Time：2019/11/11 15:50:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function getRukuInfo($params,& $service){
        if(!intval($params['sid'])){
            $service->send_user_error('sid not found');
        }
        $params['sid'] = intval($params['sid']);

        //查找数据
        $info = $this->_subModel->find($params['sid']);
        if(!$info['id']){
            $service->send_user_error('sid not in database');
        }

        $info['sid']      = $info['id'];
        $info['rukuCode'] = $info['Rk']['rukuCode'];
        $info['rukuDate'] = $info['Rk']['rukuDate'];
        $info['reason']   = $info['Rk']['reason'];
        $info['purpose']  = $info['Rk']['purpose'];
        $info['memo']     = $info['Rk']['memo'];
        $info['creater']  = $info['Rk']['creater'];
        // $info['imageId']  = explode(',', $info['imageId']);
        //查找图片的信息
        if($info['imageId']){
            $baseUrlstr = detect_uri_base();
            $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));
            $sql = "SELECT * from jichu_image where id in({$info['imageId']})";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $v) {
                $imageId[] = array(
                    'imagePath' =>$serverUrl .$v['path'],
                    'imageId'   =>$v['id'],
                );
            }
            $info['imageId'] = $imageId;
        }else{
            $info['imageId'] = array();
        }

        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelProduct= FLEA::getSingleton('Model_Jichu_Product');
        if($info['kuweiId']){
            $_tmp = $modelKuwei->find($info['kuweiId']);
            $info['kuweiName'] = $_tmp['kuweiName'];
        }

        //获取产品信息
        if($info['productId']){
            $sql = "SELECT x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$info['productId']}'";
            $_tmp = $modelProduct->findBySql($sql);
            $_tmp = $_tmp[0];
            $_tRow = array();
            $modelProduct->filedValue3($_tRow ,$_tmp);
            $_tmp['otherDesc'] = $_tRow;
            $info['Product'] = $_tmp;
            $info['proName'] = $_tmp['proName'];
        }

        unset($info['id']);
        unset($info['Rk']);
        return $info;
    }

    function getRkInfo($params,& $service){
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelProduct = FLEA::getSingleton("Model_Jichu_Product");
        if(!($params['code'])){
            $service->send_user_error('code not found');
        }
        $info = $this->_subModel->find(array('code'=>$params['code']));
        if($info){
            $info['reason']   = $info['Rk']['reason'];
            $info['purpose']  = $info['Rk']['purpose'];
            $info['memo']     = $info['Rk']['memo'];
            $info['creater']  = $info['Rk']['creater'];
            // $info['imageId']  = explode(',', $info['imageId']);
            //查找图片的信息
            if($info['imageId']){
                $baseUrlstr = detect_uri_base();
                $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));
                $sql = "SELECT * from jichu_image where id in({$info['imageId']})";
                $tmp = $this->_modelExample->findBySql($sql);
                foreach ($tmp as & $v) {
                    $imageId[] = array(
                        'imagePath' =>$serverUrl .$v['path'],
                        'imageId'   =>$v['id'],
                    );
                }
                $info['imageId'] = $imageId;
            }else{
                $info['imageId'] = array();
            }

            if($info['kuweiId']){
                $_tmp = $modelKuwei->find($info['kuweiId']);
                $info['kuweiName'] = $_tmp['kuweiName'];
            }
            
            //获取产品信息
            if($info['productId']){
                $sql = "SELECT x.*,y.kindName from jichu_product x
                    left join jichu_prokind y on x.kindId=y.id
                  where x.id = '{$info['productId']}'";
                $_tmp = $modelProduct->findBySql($sql);
                $_tmp = $_tmp[0];
                $_tRow = array();
                $modelProduct->filedValue3($_tRow ,$_tmp);
                $_tmp['otherDesc'] = $_tRow;
                $info['Product'] = $_tmp;
                $info['proName'] = $_tmp['proName'];
            }
            if($info['hzlId']){
                $info['hzlId'] = explode(',', $info['hzlId']);
            }
            unset($info['id']);
            unset($info['rukuId']);
            unset($info['Rk']);
            $modelRuku = FLEA::getSingleton('Model_Sample_Ruku');
        }else{
            $info = $modelProduct->find(array('proCode'=>$params['code']));
        }
        return $info;
    }

    /**
     * 新增入库页面获取选项
     * Time：2021年6月15日 13:21:17
     * @author lxd
     * @param 参数类型
     * @return 返回值类型
    */
    function getRukuOption($params){
        $modelRuku = FLEA::getSingleton('Model_Sample_Ruku');
        $modelKind = FLEA::getSingleton('Model_Jichu_Prokind');
        //获取后整理工艺选项
        $modelGongyi = FLEA::getSingleton('Model_Jichu_Gongyi');
        $hzlOptions = $modelGongyi->getOptions();

        //产品种类选项
        $modelProkind = FLEA::getSingleton("Model_Jichu_Prokind");
        $prokind = $modelProkind->getOptions();
        foreach ($prokind as $k => & $v) {
            $v['fileds'] = $modelKind->getFileds($v['value'] ,'all');
        }
        $formParams['Prokind']       = $prokind;
        $formParams['hzlOptions']    = $hzlOptions;
        return $formParams;
    }
    /**
     * 删除
     * Time：2019/11/11 15:50:35
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function rukuRemove($params,& $service){
        if(!intval($params['sid'])){
            $service->send_user_error('sid not found');
        }
        $params['sid'] = intval($params['sid']);

        $info = $this->_subModel->find($params['sid']);
        if(!$info['id']){
            $service->send_user_error('sid not in database');
        }

        //查找还有多少个明细信息
        $count = $this->_subModel->findCount(array('rukuId'=>$info['rukuId']));
        if($count == 1){
            //查找到对应的图片信息
            $oldInfo = $this->_modelExample->find($info['rukuId']);
            $imageIds = array_col_values($oldInfo['Products'],'imageId');
            $imageIds = join(',',$imageIds);

            $res = $this->_modelExample->removeByPkv($info['rukuId']);
        }else{
            $oldInfo = $this->_subModel->find($params['sid']);
            $res = $this->_subModel->removeByPkv($params['sid']);
            $imageIds = $oldInfo['imageId'];
        }

        //如果有图片，则删除图片
        if($imageIds){
            $imgClass = FLEA::getSingleton('Controller_Jichu_Image');
            $image = explode(',', $imageIds);
            foreach ($image as & $img) {
                $imgClass->_removeImg($img);
            }
        }

        return array('success'=>$res ? true : false ,'msg'=>'操作完成');
    }


    /**
     * 获取最新的 条码对应的入库信息和产品信息
     * Time：2019/11/21 11:02:48
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function searchByCode($params,& $service){
        if(!$params['code']){
            $service->send_user_error('param code not found');
        }

        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelProduct= FLEA::getSingleton('Model_Jichu_Product');
        $baseUrlstr = detect_uri_base();
        $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));

        //查找最新的该条码对应的信息
        $sql = "SELECT x.productId,x.code,x.proDesc,x.kuweiId,x.imageId,y.reason,y.purpose,y.rukuDate,x.memoView,x.gexing,x.hzlId,x.zuzhi,x.tanli,x.type,y.memo
            from sample_ruku2product x
            left join sample_ruku y on x.rukuId=y.id
            where x.code = '{$params['code']}'
            order by x.id desc
            limit 0,1
        ";

        $row = $this->_modelExample->findBySql($sql);
        $row = $row[0];
        if($row['kuweiId']){
            $_tmp = $modelKuwei->find($row['kuweiId']);
            $row['kuweiName'] = $_tmp['kuweiName'];
        }

        //获取产品信息
        $row['Product'] = array('imageSrc'=>array());
        if($row['productId']){
            $sql = "SELECT x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$row['productId']}'";
            $_tmp = $modelProduct->findBySql($sql);
            $_tmp = $_tmp[0];
            $_tRow = array();
            $modelProduct->filedValue4($_tRow ,$_tmp);
            $_tmp['otherDesc'] = $_tRow;
            foreach ($_tRow as $tk => & $desc) {
                $_tmp['otherDesc'][] = $tk.':'.$desc;
                $_tmp['others'][] = array('title'=>$tk  ,'value'=>$desc);
            }
            $_tmp['othersRows'] = ceil(count($_tmp['others'])/2);//用户计算显示其他信息的行数
            $_tmp['otherDesc'] = join(' ',$_tmp['otherDesc']);

            if($_tmp['pic']){
                $sql = "SELECT * from jichu_image where id in({$_tmp['pic']})";
                $tmp = $this->_modelExample->findBySql($sql);
                foreach ($tmp as & $ii) {
                    $_tmp['imageSrc'][] = $serverUrl .$ii['path'];
                }
            }

            $row['Product'] = $_tmp;
        }

        //图片信息
        $row['imageSrc'] = array();
        if($row['imageId']){
            $sql = "SELECT * from jichu_image where id in({$row['imageId']})";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $ii) {
                $row['imageSrc'][] = $serverUrl .$ii['path'];
            }
        }

        if($row['hzlId']){
            $sql = "SELECT * from jichu_gongyi where id in({$row['hzlId']})";
            $tmp = $this->_modelExample->findBySql($sql);
            $row['hzl'] = join('，',array_col_values($tmp,'gongyiName'));
        }

        //查找库存情况
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        $row['kucun'] = $modelKucun->getKucun(array(
            'productId' =>$row['productId'],
            'kuweiId'   =>$row['kuweiId'],
            'type'      =>$row['type'],
            'proDesc'   =>$row['proDesc'],
            'code'      =>$row['code'],
        ));
        $row['kucun'] = round($row['kucun'],3);
        return array('success'=>true ,'row'=>$row ,'msg'=>'获取成功');
    }

    /**
     * 以图搜样品
     * Time：2019/11/28 11:42:27
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function searchByImage($params,& $service){
        $fileImage = $_FILES['imageFile'];

        //处理图片，放到缓存目录中
        $this->setImage($fileImage ,$path ,$error_msg);
        if($error_msg){
            return array('success'=>false ,'msg'=>$error_msg);
        }
        if(!$path){
            return array('success'=>false ,'msg'=>'图片处理错误');
        }

        $isSim = FLEA::getAppInf('searchByImage');
        if(!$isSim){
            return array('success'=>false ,'msg'=>'服务器已禁用图片找布功能');
        }

        //开始请求知图网接口，得到列表；仅显示前50个，并做分析处理，如果相似度没有超多80%,舍弃结果
        $apiService = FLEA::getSingleton('Api_Lib_Req_Zhitu_ImageSim');
        $apiResponse = $apiService->searchImage(array('path'=>$path));
        $apiResponse = json_decode($apiResponse ,true);

        //删除临时目录图片内容：不返回错误结果
        if($path != '' && file_exists($path)){
            @unlink(iconv('UTF-8','gb2312',$path));
        }

        //处理相似的数据
        $list = array();
        foreach ($apiResponse['resultList'] as $key => & $v) {
            list($code ,$imageId) = explode('_' ,$v['imgName']);
            //返回第一个数据或者相似度大于80%的数据
            if($v['score'] > 0.8 || count($list) < 1){
                $list[] = array('imageId'=>$imageId ,'score'=>$v['score']);
            }
        }

        //查找图片所在位置和分析数据
        $modelProduct = FLEA::getSingleton('Model_Jichu_Product');
        $modelKuwei = FLEA::getSingleton('Model_Jichu_Kuwei');
        $modelImage = FLEA::getSingleton('Model_Jichu_Image');
        $modelKucun = FLEA::getSingleton('Model_Sample_Kucun');
        $baseUrlstr = detect_uri_base();
        $serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));

        $rows = array();
        foreach ($list as & $l) {
            //先查询基础档案
            $sql = "SELECT id from jichu_product where find_in_set({$l['imageId']} , pic) and isSim='1'";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $v) {
                $rows[] = array(
                    'imageId'    =>$l['imageId'],
                    'score'      =>$l['score'],
                    'productId'  =>$v['id'],
                    'ruku2proId' =>0,
                );
            }

            //查找样品中的图片信息
            $sql = "SELECT x.id,x.rukuId,x.productId from sample_ruku2product x
            left join jichu_product y on x.productId=y.id
            where y.isSim='1' and find_in_set({$l['imageId']} , x.imageId) ";
            $tmp = $this->_modelExample->findBySql($sql);
            foreach ($tmp as & $v) {
                $rows[] = array(
                    'imageId'    =>$l['imageId'],
                    'score'      =>$l['score'],
                    'productId'  =>$v['productId'],
                    'ruku2proId' =>$v['id'],
                    'rukuId'     =>$v['rukuId'],
                );
            }
        }

        //查找这些数据的详细信息
        foreach ($rows as & $v) {
            $v['score'] = round($v['score'] ,5);
            $v['score'] = ($v['score']*100).'%';
            //产品明细
            $sql = "select x.*,y.kindName from jichu_product x
                left join jichu_prokind y on x.kindId=y.id
              where x.id = '{$v['productId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $v['proCode']  = $tmp[0]['proCode'];
            $v['proName']  = $tmp[0]['proName'];
            $v['kindName'] = $tmp[0]['kindName'];
            //特殊处理下产品数据
            $_tRow = array();
            $modelProduct->filedValue3($_tRow ,$tmp[0] ,$filedsSingle);
            // $v['otherDesc'] = $_tRow;
            foreach ($_tRow as $tk => & $desc) {
                $v['otherDesc'][] = $tk.':'.$desc;
                $v['others'][] = array('title'=>$tk  ,'value'=>$desc);
            }
            $v['othersRows'] = ceil(count($v['others'])/2);//用户计算显示其他信息的行数
            $v['otherDesc'] = join(' ',$v['otherDesc']);

            //如果有入库信息，再获取其中的详细数据
            $sql = "SELECT * from sample_ruku2product where id='{$v['ruku2proId']}'";
            $tmp = $this->_modelExample->findBySql($sql);
            $tmp = $tmp[0];
            $v['type']      = strval($tmp['type']);
            $v['proDesc']   = strval($tmp['proDesc']);
            $v['memoView']  = strval($tmp['memoView']);
            $v['code']      = strval($tmp['code']);
            $v['kuweiName'] = '';

            //查找库存
            $kWhere = array();
            $kWhere['productId'] = $v['productId'];
            if($v['ruku2proId']){
                $kWhere['type']    = $v['type'];
                $kWhere['proDesc'] = $v['proDesc'];
                $kWhere['code']    = $v['code'];
            }
            $v['kucun'] = $modelKucun->getKucun($kWhere);
            $v['kucun'] = $v['kucun'] + 0;
            if($v['imageId']){
                $_tmp = $modelImage->find($v['imageId']);
                $v['imagePath'] = $serverUrl.($_tmp['smallPath'] ? $_tmp['smallPath'] : $_tmp['path']);
            }
        }

        return array('success'=>true ,'row'=>$rows,'pageCount'=>count($rows),'total'=>count($rows));
    }

    //处理上传的图片信息，放到服务器临时目录缓存下
    function setImage($fileImage ,& $path,& $error){
        if(!$fileImage){
            $error = "imageFile not exists";
            return false;
        }

        //上传文件的类型
        $uploadType = array('jpg','jpeg','png');
        $pathinfo = pathinfo($fileImage['name']);
        $extType = $pathinfo['extension'];
        // dump($pathinfo);exit;
        if(!in_array($extType , $uploadType)){
            $error = "imageFile is not image";
            return false;
        }
        //上传文件的最大值
        $max_size = 12 * 1024 * 1024; //12M
        if($fileImage['size'] > $max_size){
            $error = "imageFile > 12M";
            return false;
        }

        //获取图片信息
        $size = getimagesize($fileImage['tmp_name']);
        $width  = $size[0];
        $height = $size[1];

        $pathRoot = 'upload/tmp/';
        $rand = rand(10000, 99999);
        $randNameSmall = date('ymdHis') . $rand.'.'.$extType;
        $imagePathSmall = $pathRoot.$randNameSmall;

        //缩略图
        FLEA::loadClass('FLEA_Helper_Image');
        $img = & FLEA_Helper_Image::createFromFile($fileImage['tmp_name'], $extType);
        //计算压缩比例
        $max = 800;
        if($width > $height && $width > $max){
            $rate = $max / $width;
            $height2 = $height * $rate;
            $width2  = $max;
        }elseif($height > $width && $height > $max){
            $rate = $max / $height;
            $height2 = $max;
            $width2  = $width * $rate;
        }else{
            $height2 = $height;
            $width2  = $width;
        }

        $img->resampled($width2 , $height2);
        $img->saveAsJpeg($imagePathSmall , 90);

        //回值
        $path = $imagePathSmall;

        return true;
    }

    function CreateProCode($head,$next,$tblName,$fieldName){
        $m = & FLEA::getSingleton('Model_Acm_User');
        $m->force_master = true;

        $sql = "select {$fieldName} from {$tblName} where {$fieldName} like '{$head}{$next}_____' order by {$fieldName} desc limit 0,1";
        $_r = $m->findBySql($sql);
        $row = $_r[0];
        $init = $head.$next.'00001';
        if(empty($row[$fieldName])) return $init;
        if($init>$row[$fieldName]) return $init;
        // dump($init);exit;
        //自增1
        $max = substr($row[$fieldName],-5);
        $pre = substr($row[$fieldName],0,-5);

        return $pre .substr(100001+$max,1);
    }

}

?>